package com.lxp.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxp.common.R;
import com.lxp.entity.Category;
import com.lxp.service.CategoryService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lxp
 * @Motto 每天一行小代码，健康幸福学JAVA：
 * @create 2022-08-24 10:49
 * @Description:  分类管理
 */

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 添加菜品 和 套餐
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        boolean flag = categoryService.save(category);
        if (flag){
            return R.success("添加菜品成功");
        }
        return R.error("添加菜品失败");
    }

    /**
     * 分页功能查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<IPage> page(Integer page,Integer pageSize){
        // 分页构造器
        IPage<Category> iPage = new Page<>(page,pageSize);
        // 条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        // 添加排序条件，根据sort进行排序
        lqw.orderByAsc(Category::getSort);
        // 进行分页查询
        categoryService.page(iPage, lqw);

        return R.success(iPage);
    }

    /**
     * 修改菜品 和套餐
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        boolean flag = categoryService.updateById(category);
        if (flag){
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }

    /**
     * 根据id删除分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(Long ids){
        System.out.println(ids);
        categoryService.delete(ids);
        return R.success("分类信息删除成功");
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> getList(Category category){
        // 条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        // 添加条件
        lqw.eq(category.getType() != null,Category::getType,category.getType());
        // 添加排序条件
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> categoryList = categoryService.list(lqw);

        return R.success(categoryList);
    }
}
